﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Model;
using BllFactory;
using IBLL;
using ETWebApi2.Models;
using System.Web;
using System.IO;

namespace ETWebApi2.Controllers
{
    [Route("upload")]
    public class UploadController : ApiController
    {
        private IPartnerRelation_tbService m_partnerService = ServiceFactory.CreatService<IPartnerRelation_tbService>();
        private ICUser_tbService m_cuserService = ServiceFactory.CreatService<ICUser_tbService>();
        private ICustomers_tbService m_customerService = ServiceFactory.CreatService<ICustomers_tbService>();
        private IFiles_tbService m_filesServic = ServiceFactory.CreatService<IFiles_tbService>();

        /// <summary>
        /// 没有搜索条件时也可以访问此路径
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetLoadPartner(string query = "")
        {
            //无锁测试  
            //Session["LockNum"] = "3008054"; 
            JwtAuthObject info = HttpContext.Current.Session["UserInfo"] as JwtAuthObject;
            if (info == null)
                return ObjectToJson.toJson(new { status = 201, data = "session为null" });
            List<UploadModel> uploadInfo = new List<UploadModel>();
            if (!string.IsNullOrEmpty(query))
            {
                //List<VIEW_PR> partnerList = prService.GetList(p => p.SelfCompanyId == 12134 && p.State == 1 && (p.Name.Contains(query) || p.address.Contains(query)));
                IVIEW_PRService prService = ServiceFactory.CreatService<IVIEW_PRService>();
                List<VIEW_PR> partnerList = prService.GetList(p => p.SelfCompanyId == info.CurentCopmpanyId && p.State == 1 && (p.Name.Contains(query) || p.address.Contains(query)));

                List<PartnerRelation_tb> partners = new List<PartnerRelation_tb>();
                if (partnerList.Count > 0)
                {
                    foreach (var p in partnerList)
                    {
                        PartnerRelation_tb partner = new PartnerRelation_tb()
                        {
                            Id = p.Id,
                            SelfCompanyId = p.SelfCompanyId,
                            PartnerId = p.PartnerId,
                            State = p.State,
                            touser = p.touser,
                            Receiver = p.Receiver,
                            Time = p.Time
                        };
                        partners.Add(partner);
                    }
                }
                if (partners.Count > 0)
                    uploadInfo = BuiltInfo(partners);
            }
            else
            {
                if (HttpContext.Current.Request.Files.Count == 0)
                    uploadInfo = MyPartner(info.CurentCopmpanyId);
            }
            return ObjectToJson.toJson(new { status = 200, data = new { total = uploadInfo.Count, rows = uploadInfo } });
        }

        //我的伙伴
        private List<UploadModel> MyPartner(int currenyCid)
        {
            List<UploadModel> uploadinfo = new List<UploadModel>();
            List<PartnerRelation_tb> partners = m_partnerService.GetList(p => p.SelfCompanyId == currenyCid && p.State == 1);
            if (partners.Count > 0)
            {
                uploadinfo = BuiltInfo(partners);
            }
            return uploadinfo;
        }
        /// <summary>
        /// 构建合作伙伴信息
        /// </summary>   
        /// <param name="partners">搜索到的伙伴</param>
        /// <returns></returns>
        private List<UploadModel> BuiltInfo(List<PartnerRelation_tb> partners)
        {
            List<UploadModel> uploadeInfo = new List<UploadModel>();
            if (partners.Count > 0)
            {
                foreach (var p in partners)
                {
                    List<CUser_tb> cuser;
                    if (!string.IsNullOrEmpty(p.Receiver) && p.Receiver != " ")
                    {
                        cuser = new List<CUser_tb>();
                        string[] arr = p.Receiver.Split('|');
                        foreach (string c in arr)
                        {
                            if (new BaseClass().CheckNumber(c))
                            {
                                CUser_tb cu = m_cuserService.GetList(u => u.Id == Convert.ToInt32(c)).FirstOrDefault();
                                if (cu != null && cu.State > 0)
                                    cuser.Add(cu);
                            }
                        }
                    }
                    else
                        //没设置,则是所有有接受权限的人  
                        cuser = m_cuserService.GetList(u => u.CompanyId == p.PartnerId && ((u.Permission == "01" || u.Permission == "11") || u.Down == 1) && u.State == 1);
                    if (cuser.Count > 0)
                    {
                        Customers_tb cus = m_customerService.GetList(c => c.Id == p.PartnerId).FirstOrDefault();
                        if (cus == null)
                            break;
                        UploadModel up = new UploadModel();
                        up.CompanyId = cus.Id;
                        up.CompanyName = cus.Name;
                        List<UploadUserModel> user = new List<UploadUserModel>();
                        for (int i = 0; i < cuser.Count; i++)
                        {
                            UploadUserModel Upuser = new UploadUserModel()
                            {
                                Id = cuser[i].Id,
                                UserName = cuser[i].UserName,
                                Remark = cuser[i].Remark
                            };
                            user.Add(Upuser);
                        }
                        up.Users = user;
                        uploadeInfo.Add(up);
                    }
                }
            }
            return uploadeInfo;
        }

        
        [HttpPost, Route("saveas")]
        public HttpResponseMessage PostSaveAs()
        {
            //另存接口函数，是不post数据的 
            //合作伙伴的公司id
            string common = HttpContext.Current.Request.Params["common"];
            string filename = HttpContext.Current.Request.Params["file"];
            string[] files = filename.Split('|');
            JwtAuthObject info = HttpContext.Current.Session["UserInfo"] as JwtAuthObject;
            //发送成功或失败的消息提示  成功:文件个数 大小 压缩包名称 
            if (files.Length >= 2)
            {
                string degree = files[files.Length - 1];
                PartnerRelation_tb pRelation = m_partnerService.GetList(p => ((p.SelfCompanyId == info.CurentCopmpanyId && p.PartnerId == int.Parse(common))) && p.State >= 0).FirstOrDefault();
                if (pRelation==null)
                    return  ObjectToJson.toJson(new {status=201,error="找不到伙伴信息" } );
                else
                {
                    for (int i = 1; i < files.Length; i++)
                    {
                        Files_tb afile = new Files_tb(info.UserId, int.Parse(common), files[i - 1], DateTime.Now, 0, HttpContext.Current.Request.UserHostAddress, float.Parse(degree), "", pRelation.touser);                        afile.dIP = HttpContext.Current.Request.UserHostAddress;
                        afile.dTime = DateTime.Now;
                        afile.dUserId = info.UserId; // 存token
                        m_filesServic.Add(afile);  //文件另存为,实际上没有上传文件,所以下载人是自己
                    }
                    return ObjectToJson.toJson(new { status=200,rel=true,fileCount = files.Length, fileOneName = files[0].Substring(0, files[0].LastIndexOf(".")) });
                }
            }
            else
                return ObjectToJson.toJson(new { status = 201, error = "另存出错" });
        }

        /// <summary>
        /// 文件上传  
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost, Route("Upload/UploadZip")]
        public HttpResponseMessage PostUpload()
        {
            HttpResponseMessage hm = new HttpResponseMessage();
            hm = ObjectToJson.toJson("上传失败");
            try
            {
                new WriteBug().WriteBugLog("Upload/UploadZip", "开始文件上传");
                //这是收到了ETCAD程序post来的数据 
                HttpContext context = HttpContext.Current;
                string touser = context.Request.Params["common"];//下载文件的人
                string locknum = context.Request.Params["locknum"];//锁内编号
                string degree = context.Request.Params["degree"];
                string filenum = context.Request.Params["filenum"];//文件 

                HttpPostedFile file = HttpContext.Current.Request.Files["file"];
                HttpPostedFileBase uploadfile = new HttpPostedFileWrapper(file) as HttpPostedFileBase;
                if (uploadfile == null)
                    return hm = ObjectToJson.toJson("no: 请选择文件");
                if (uploadfile.FileName == "")
                    return hm = ObjectToJson.toJson("no: 请选择文件");

                JwtAuthObject info = HttpContext.Current.Session["UserInfo"] as JwtAuthObject;
                CUser_tb user = m_cuserService.GetList(u => u.Id == info.UserId).FirstOrDefault();

                if (user != null)
                {
                    string rootPath = HttpContext.Current.Server.MapPath("/file");
                    string dirPath = rootPath + "\\" + DateTime.Now.DayOfYear.ToString() + "\\";

                    if (file != null)
                    {
                        if (!Directory.Exists(dirPath))
                        {
                            Directory.CreateDirectory(dirPath);
                        }
                        hm = DealMultiFiles(file, touser, locknum, dirPath);
                    }
                }                
            }
            catch (Exception e)
            {
                new WriteBug().WriteBugLog("Upload/UploadZip 异常", e.Message);
            }
            return hm;

        }

        /// <summary>
        /// 获得能打开文件的人mac  
        /// </summary> 将获取数据传给ETCAD  
        /// <param name="partnerId">合作者的companyId</param>
        [HttpGet, Route("PartnerCompanyInfo")]
        public HttpResponseMessage PartnerCompanyInfo(int partnerId)
        {
            string mac = "";
            JwtAuthObject info = HttpContext.Current.Session["UserInfo"] as JwtAuthObject;
            if (!string.IsNullOrEmpty(partnerId.ToString()) && info != null)
            {
                //加载合作伙伴时  selfid为自己  还有partnerid也为自己的  （我加的  别人加我的  都算是合作伙伴）？
                PartnerRelation_tb pRelation = m_partnerService.GetList(p => p.SelfCompanyId == info.CurentCopmpanyId && p.PartnerId == partnerId && p.State==1).FirstOrDefault();
                if (pRelation != null)
                {
                    string mainLock = "";
                    string lockType = "";
                    if (GetMainLock(Convert.ToInt32(pRelation.PartnerId), ref mainLock, ref lockType))
                    {
                        if (!string.IsNullOrEmpty(pRelation.touser))//指定了能打开文件的人
                        {
                            string[] arr = pRelation.touser.Split('|');
                            foreach (string s in arr)
                            {
                                CUser_tb cu = m_cuserService.GetList(u => u.Id == Convert.ToInt32(s)).FirstOrDefault();
                                if (cu != null)
                                {
                                    mac += cu.MAC;
                                }
                            }
                        }
                        //锁号，锁类型，版本，备用，广告，Level(等级  0 -- 高级 1-- 低级),mac地址 "OK|" + mainLock + "|" + lockType + "|1.0|||" + mac  
                        return ObjectToJson.toJson(new { result = "OK|" + mainLock + "|" + lockType + "|1.0|" + pRelation.Level + "||" + mac.Trim() });
                    }
                    else
                        return ObjectToJson.toJson(new { result = "该伙伴拥有多把锁，暂时不能接收文件，请联系布易科技！" });
                }
                else
                    return ObjectToJson.toJson(new { result = "无效的合作方" });
            }
            return ObjectToJson.toJson(new { result = "数据错误" });
        }

        //获取主锁   
        private bool GetMainLock(int partnerId, ref string mainLock, ref string lockType)
        {
            ILocks_tbService lockservice = ServiceFactory.CreatService<ILocks_tbService>();
            List<Locks_tb> locks = lockservice.GetList(l => l.lstate != 3 && l.customerId == partnerId && (l.lockUseType == "入门锁" || l.lockUseType == "ULSG" || l.lockUseType == "BAG" || l.lockUseType == "ET"));
            if (locks.Count == 0)
                return false;
            else if (locks.Count == 1)
            {
                mainLock = locks[0].lockInsideNum;
                lockType = locks[0].lockUseType;
                return true;
            }
            else
            {
                Customers_tb cus = m_customerService.GetList(c => c.Id == partnerId).FirstOrDefault();
                if (cus != null)
                {
                    if (cus.LockCode == 0)
                        return false;
                    mainLock = cus.LockCode.ToString();
                    lockType = locks[0].lockUseType;
                    return true;
                }
            }
            return false;
        }

        //上传的压缩包,不管是单文件还是多文件都是这个函数处理
        private HttpResponseMessage DealMultiFiles(HttpPostedFile file, string touser, string locknum, string dirPath)
        {
            string fileName = file.GetHashCode().ToString();// //将文件的哈希数作为压缩包文件名以防重名

            JwtAuthObject info = HttpContext.Current.Session["UserInfo"] as JwtAuthObject;

            file.SaveAs(dirPath + fileName + ".zip");//保存总的压缩包  重命名为相应的哈希值（以防有重名问题）
            List<string> fileNameLsit = new List<string>();//得到源文件名 
            DotNetZip.DecomPression(dirPath + fileName + ".zip", dirPath, true, fileNameLsit);//将文件解压到指定目录中
            bool bSendSm = DateTime.Now.Hour < 20 && DateTime.Now.Hour >= 8;
            foreach (string Name in fileNameLsit)
            {
                if (File.Exists(dirPath + Name))
                {
                    FileInfo f = new FileInfo(dirPath + Name);
                    CUser_tb user = m_cuserService.GetList(u => u.Id == info.UserId).FirstOrDefault(); //存Token
                    //CUser_tb user = cuserService.GetList(u => u.Id == 364).FirstOrDefault(); //测试

                    int id = AddFiles(user, f.Name, int.Parse(f.Length.ToString()), touser, locknum, bSendSm);//建立文件记录  
                    if (id > 0)
                    {
                        bSendSm = false;
                        f.MoveTo(dirPath + id.ToString() + f.Extension);//重命名
                    }
                }
            }
            DotNetZip.DeleteFile(dirPath + fileName + ".zip");//删除原始压缩包
            return ObjectToJson.toJson(new { rel = true, fileName = fileNameLsit, fileCount = fileNameLsit.Count, filesize = new BaseClass().ChangeUint(file.ContentLength) });

            //return ObjectToJson.toJson(new { rel = true, fileName = Path.GetFileName(file.FileName), fileCount = fileNameLsit.Count, filesize = new BaseClass().ChangeUint(file.ContentLength) });
        }

        /// <summary>
        /// 添加文件记录,下载记录,发送短信
        /// </summary> 
        /// <param name="uId">上传用户ID</param>
        /// <param name="Attachment">附件路径</param>
        /// <param name="Length">文件大小 单位M</param>
        /// <param name="bSendSm">是否发送通知短信</param>
        private int AddFiles(CUser_tb sendUser, string Attachment, int Length, string touser, string locknum, bool bSendSm)
        {
            if (!string.IsNullOrEmpty(touser))
            {
                string[] users = touser.Split('|');
                CUser_tb cu = m_cuserService.GetList(u => u.Id == Convert.ToInt32(users[0])).FirstOrDefault(); //为了获得接收方的公司ID
                if (null != cu)
                {
                    string degree = HttpContext.Current.Request.Params["degree"];
                    if (degree == null)
                        degree = "1";

                    //获得对方能够打开文件的员工的mac地址  
                    PartnerRelation_tb pRelation = m_partnerService.GetList(p => ((p.SelfCompanyId == sendUser.CompanyId && p.PartnerId == cu.CompanyId)) && p.State >= 0).FirstOrDefault();
                    if (pRelation != null)
                    {
                        Files_tb newfile = new Files_tb(sendUser.Id, Convert.ToInt32(cu.CompanyId), Attachment, DateTime.Now, Length, HttpContext.Current.Request.UserHostAddress, float.Parse(degree), "", pRelation.touser);
                        if (m_filesServic.Add(newfile))
                            AddFileDownLoadLog(sendUser, cu, newfile, users, touser, bSendSm);
                        return newfile.Id;
                    }
                    else
                    {
                        return 0;
                    }
                }
            }
            else if (!string.IsNullOrEmpty(locknum))//全选
            {
            }
            return 0;
        }

        /// <summary>
        /// 添加文件记录,下载记录,发送短信
        /// </summary>
        /// <param name="uId">上传用户ID</param>
        /// <param name="Attachment">附件路径</param>
        /// <param name="Length">文件大小 单位M</param>
        /// <param name="bSendSm">是否发送通知短信</param>
        private void AddFileDownLoadLog(CUser_tb sendUser, CUser_tb firstUser, Files_tb newfile, string[] users, string touser, bool bSendSm)
        {
            bool res = false;
            string sql = "";
            foreach (var userId in users)
            {
                int duser = Convert.ToInt32(userId);
                sql += string.Format("insert into FileDownLoadLog_tb(DUser,FileId,dCount) values({0},{1},0)", duser, newfile.Id);
            }
            try
            {
                using (var context = new MyETLockContext())
                {
                    if (context.Database.ExecuteSqlCommand(sql) > 0)
                        res = true;
                    else
                        res = false;
                }
            }
            catch (Exception ex)
            {
                string me = ex.Message;
                throw;
            }
            #region  测试期间不发短信
            if (res)
                if (bSendSm)
                {
                    ToSendSM(users, touser, firstUser, sendUser);
                }
            #endregion
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="users"></param>
        /// <param name="touser"></param>
        /// <param name="firstUser"></param>
        /// <param name="sendUser"></param>
        private void ToSendSM(string[] users, string touser, CUser_tb firstUser, CUser_tb sendUser)
        {
            //得到可以接收短信的用户的id的集合
            List<string> phones = new List<string>();
            if (users.Length > 1)
            {
                string[] idsets = touser.Split('|');
                List<CUser_tb> cusers = m_cuserService.GetList(u => u.ReadSM == 1 && u.Phone.Length == 11 && idsets.Contains(u.Id.ToString())).OrderByDescending(u => u.Tag).ToList();
                if(cusers.Count>0)
                {
                    for (int i = 0; i < cusers.Count; i++)
                    {
                        if(!string.IsNullOrEmpty(cusers[i].Phone))
                            phones.Add(cusers[i].Phone);
                    }
                }
               
            }
            else
            {
                phones = new List<string>();
                if (firstUser.ReadSM == 1 && firstUser.Phone.Length == 11)
                    phones.Add(firstUser.Phone);
            }
            if (phones.Count > 0)
            {
                //已经发送过的手机,用于减少重复发送短信
                List<string> old_phones = HttpContext.Current.Session["allPhone"] as List<string>;
                if (old_phones == null)
                {
                    old_phones = new List<string>();
                    HttpContext.Current.Session["allPhone"] = old_phones;
                }
                if (!FindPhone(phones, old_phones))
                {
                    string param = string.Format("&p1={0}({1})", m_customerService.GetList(c => c.Id == sendUser.CompanyId).FirstOrDefault().Name, sendUser.UserName);
                    SendMessage.SendSM(phones[0], "15ImtaGKz0XN", param);
                    old_phones.Add(phones[0]);
                }
            }
        }

        private bool FindPhone(List<string> phones, List<string> old_phones)
        {
            for (int i = 0; i < phones.Count; i++)
            {
                for (int k = 0; k < old_phones.Count; k++)
                {
                    if (phones[i] == old_phones[k])
                        return true;
                }
            }
            return false;
        }

        [HttpGet,Route("writepara")]
        public void GetUpLoadPara()
        {
            string para = HttpContext.Current.Request.Params["uploadPara"];
            int type = Convert.ToInt32(HttpContext.Current.Request.Params["type"]);
            if(type==0)
                new WriteBug().WriteBugLog("另存为传参数:", para);
            else
                new WriteBug().WriteBugLog("文件上传参数:", para);

        }
    }
}
